package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisMessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Member;
import cn.itcast.service.MemberService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/*
 *Author:TH
 *Dete:2019/10/2819:03
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;
    @Autowired
    private HttpServletResponse response;

    //短信登录
    @RequestMapping("/login")
    public Result login(@RequestBody Map map){
        //获取手机号
        String telephone = (String) map.get("telephone");
        //获取输入的验证码
        String validateCode = (String) map.get("validateCode");

        //取出redis中的验证码
        String validateRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        //判断是否匹配
        if (validateRedis!=null&&validateCode!=null&&validateCode.equals(validateRedis)){
            //匹配成功,验证用户是否是会员
            Member member = memberService.findByTelephone(telephone);
            if (member==null){
                //非会员,注册会员
                member =new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //向客户端写入Cookie,记录手机号码以及会员号码
            Cookie cookie = new Cookie("logintelephone",telephone+"@"+member.getId());
            //存活七天
            cookie.setMaxAge(60*60*24*7);
            cookie.setPath("/");
            response.addCookie(cookie);

            //将用户信息存入redis数据库
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);

        }else{
            //验证码不匹配
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

}
